require 'rubygems'
require 'mysql'
require 'singleton'
require 'erb'
#require 'ruby-debug'
require 'yaml'

=begin
add 20100801
添加工厂方法,直接创建各环境下的DB连接,具体可看test_db_help.rb
tao_hidoudou, hidoudou_staging, hidoudou_production
-----------------------------------------------------
=end

module DBHelp
	class DBHelp
		#include Singleton  
		
		TAO_HIDOUDOU_CONF = {'database' => 'tao_hidoudou'}
		STAGING_CONF = { 'database' => 'hidoudou_staging' }
		PRODUCTION_CONF = { 'database' => 'hidoudou_production' }
		
		def initialize(evn = "development", db_config_file = "../config/database.yml", db_opt = {})
			puts db_config_file
			config = YAML.load(ERB.new(File.read(db_config_file)).result) if db_opt.empty?
			
			db_config = {}
			if db_opt.empty? then	db_config = config[evn]
			else	db_config = db_opt 
			end
			
			db_config['host'] = "118.126.2.138" if db_config['host'].nil?
			db_config['username'] = "root" if db_config['username'].nil?
			db_config['password'] = 'admin' if db_config['password'].nil?
			db_config['encoding'] = 'utf8' if db_config['encoding'].nil?
			raise "请指定数据库！" if db_config['database'].nil?
			
			#debugger
			@dbh = Mysql.init
			@dbh.options(Mysql::SET_CHARSET_NAME, db_config['encoding'])
			@dbh = Mysql.real_connect(db_config['host'], db_config['username'], db_config['password'], db_config['database'], 3306) #连接数据库
			#@dbh = Mysql.real_connect('localhost', 'root', 'admin','ladyshop', 3306) #连接数据库
			@dbh.query("SET NAMES #{db_config['encoding']}")
		end
		
		def self.out_initialize(db_opt = {})
			new("", "", db_opt)
		end
		
		def self.create(db_opt = {})
			new("", "", db_opt)
		end
		
		def self.create_tao_hidoudou() 
			create(TAO_HIDOUDOU_CONF)
		end
		
		def self.create_staging()
			create(STAGING_CONF)
		end
		
		def self.create_production()
			create(PRODUCTION_CONF)
		end
	
		def query(sql)
			begin
				#puts sql  
				@dbh.query(sql)
			rescue Mysql::Error=>e
				puts "Error code:#{e.errno} - sql:#{sql}"
			end
		end
		
		def escape(param)
			return '' if param.nil?
			return param.gsub("'", "''")
		end
		
		def build_param(param, end_str = "")
			"'#{escape(param)}'#{end_str}"
		end
	
		def build_sql(hash = {})
			fields = ""
			values = ""
			i = 0
			hash.each_pair do |key, value|
				next if key.to_s == "table"
				i += 1
				fields += key.to_s
				fields += ", " unless i == hash.length - 1
				values += "'#{escape(value.to_s)}'"
				values += ", " unless i == hash.length - 1
			end
			sql = "insert into #{hash['table']} ("
			sql += fields + ") "
			sql += "values (" + values + ");"
		end
	
		def close
			@dbh.close if @dbh 
		end
		
	end #~ end class
end
